package com.yidu.t299.controller.chr;

import com.yidu.t299.domain.chr.*;
import com.yidu.t299.domain.chr.Class;
import com.yidu.t299.service.chr.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

/**
 * @author chr
 * @version 1.0.0
 */
@RestController
public class GradeController {
    @Autowired
    private GradesBiz gradesBiz;
    @Autowired
    private GradeBiz gradeBiz;
    @Autowired
    private LessonBiz lessonBiz;
    @Autowired
    private StudentManageBiz studentManageBiz;
    @Autowired
    private SchoolBiz schoolBiz;
    @Autowired
    private ClassBiz classBiz;
    @Autowired
    private GradessBiz gradessBiz;


    /**
     * 跳转并保存下拉框数据(实现动态下拉框功能)
     */
    @RequestMapping("grade/init")
    public ModelAndView saveSelect(){
        List<Lesson> lessonsList = lessonBiz.selectAll();//得到所有课程信息
        List<School> schoolList = schoolBiz.selectAll();//得到所有校区信息
        ModelAndView mv = new ModelAndView();
        mv.setViewName("gradeCRUD");//跳转的页面
        mv.addObject("lessonsList",lessonsList); //保存课程信息
        mv.addObject("schoolList",schoolList); //保存校区信息
        return mv;
    }

    @RequestMapping("grade/in")
    public ModelAndView boxSelect(){
        List<Class> classList = classBiz.selectAll();
        ModelAndView mv = new ModelAndView();
        mv.setViewName("gradesCRUD");//跳转的页面
        mv.addObject("classList",classList);
        return mv;
    }

    @RequestMapping("grade/int")
    public ModelAndView allSelect(){
        List<Class> classList = classBiz.selectAll();
        List<Lesson> lessonsList = lessonBiz.selectAll();//得到所有课程信息
        List<School> schoolList = schoolBiz.selectAll();//得到所有校区信息
        ModelAndView mv = new ModelAndView();
        mv.setViewName("gradessCRUD");//跳转的页面
        mv.addObject("classList",classList);
        mv.addObject("lessonsList",lessonsList); //保存课程信息
        mv.addObject("schoolList",schoolList); //保存校区信息
        return mv;
    }


    /**
     * 分页查询显示数据在表格中
     *
     * @param limit 页码
     * @param page  每页的行数
     * @param schoolName 校区名称
     * @param studentName 学员名称
     * @return 映射集合对象
     */
    @GetMapping("grade/restful_grade")
    public Map<String, Object> findAll(int limit, int page, String studentName,String schoolName) {
        // 根据校区名称或学员名称得到条件字符串
        String condition = gradeBiz.getCondition(studentName,schoolName);
        // 按条件统计总记录行数
        int count = gradeBiz.selectCount(condition);
        // 按条件分页查询
        List<Grade> schoolList = gradeBiz.selectByPage(limit, page-1, condition);
        // 创建一个map，用来存放返回给layui组件需要的键值对
        Map<String, Object> mapData = new HashMap<String, Object>();
        //在映射集合中添加key为code，值为0的状态码
        mapData.put("code", 0);
        //在映射集合中添加key为msg，值为空字符串的响应信息字符串
        mapData.put("msg", "");
        //在映射集合中添加为count，值为总行数的映射
        mapData.put("count", count);
        //在映射集合中添加key为data，值为成绩对象集合的映射
        mapData.put("data", schoolList);

        //把映射集合响应到客户端
        return mapData;
    }

    /**
     * 添加一个新成绩
     *
     * @param dataStr 成绩编号字符串
     * @return 提示信息字符串
     */
    @PostMapping("grade/restful_grade")
    public String addEmp(@RequestBody String dataStr) {
        //将字符串分割成字符串数组
        String[] data = dataStr.split("/");
        //根据名称得到对应的主键编号
        data[1] = studentManageBiz.selectByName(data[1]);
        data[2] = lessonBiz.selectByName(data[2]);
        //转换成整型数组
        Integer[] fields;
        if(data[1]!=null && data[1].trim().length()>0 && data[2]!=null && data[2].trim().length()>0){
            fields = StringToInt(data);
        }else {
            return "add-failure";
        }
        //调用业务层实现新增员成绩，并返回正确与否字符串
        return gradeBiz.insert(fields[0],fields[1],fields[2],fields[3]) > 0 ? "add-success" : "add-failure";
    }

    /**
     * 将字符串数组转换成整型数组
     * @param arr 字符串数组
     * @return 整型数组
     */
    public Integer[] StringToInt(String[] arr){
        Integer[] array = new Integer[arr.length];
        for (int i = 0; i < arr.length; i++) {
            array[i] = Integer.parseInt(arr[i]);
        }
        return array;
    }


    /**
     * 修改成绩信息
     *
     * @param dataStr 成绩对象
     * @return 提示信息字符串
     */
    @PutMapping("grade/restful_grade")
    public String updateEmp(@RequestBody String dataStr) {
        //将字符串分割成字符串数组
        String[] data = dataStr.split("/");
        //根据名称得到对应的主键编号
        data[1] = studentManageBiz.selectByName(data[1]);
        data[2] = lessonBiz.selectByName(data[2]);
        //转换成整型数组
        Integer[] fields;
        if(data[1]!=null && data[1].trim().length()>0 && data[2]!=null && data[2].trim().length()>0){
            fields = StringToInt(data);
        }else {
            return "update-failure";
        }
        //调用业务层实现新增员成绩，并返回正确与否字符串
        return gradeBiz.updateByPrimaryKey(fields[0],fields[1],fields[2],fields[3]) > 0 ? "update-success" : "update-failure";
    }

    /**
     * 根据成绩编号删除成绩信息
     *
     * @param gradeId 成绩编号
     * @return 提示信息字符串
     */
    @DeleteMapping("grade/restful_grade/{gradeId}")
    public String deleteEmpById(@PathVariable("gradeId") int gradeId) {
        //调用业务层实现删除成绩，并返回正确与否字符串
        return gradeBiz.deleteByPrimaryKey(gradeId) > 0 ? "delete-success" : "delete-failure";
    }

    /**
     * 根据多个成绩编号批量删除校区
     * 此方法使用put请求替代delete，put可以带请求体
     *
     * @param gradeIdStr 多个成绩编号字符串
     * @return 提示信息字符串
     */
    @PutMapping("grade/batchDel")
    public String deleteEmpByManyId(@RequestParam String gradeIdStr) {
        //按,号分割成字符串数组
        String[] strArrays = gradeIdStr.split(",");
        //循环按成绩编号删除
        for (String str : strArrays) {
            //只要有一个删除错误就直接返回错误信息字符串
            if (gradeBiz.deleteByPrimaryKey(Integer.parseInt(str)) < 1) {
                return "delete-failure";
            }
        }
        return "delete-success";
    }

    /**
     * 测试
     * @return
     */
    @RequestMapping("grade/test")
    public List<Grades> find(){
      List<Grades> gradesList = gradesBiz.selectByLesson(1,5,null);
        return selectById(gradesList);
    }

    /**
     * 循环添加成绩
     * @param gradesList
     * @return
     */
    public List<Grades> selectById(List<Grades> gradesList){

        int rowe = 1;
        int index = 1;
        if (gradesList != null) {
            for (Grades grades : gradesList) {
                grades.setLessonGradeone(gradesBiz.selectByStudentName(grades.getStudentId(), 1));
                grades.setLessonGradetwo(gradesBiz.selectByStudentName(grades.getStudentId(), 2));
                grades.setLessonGradethree(gradesBiz.selectByStudentName(grades.getStudentId(), 3));
                grades.setSumlesson(gradesBiz.selectSumlesson(grades.getStudentId()));
            }

        }
        gradesList.sort(Comparator.comparing(Grades::getSumlesson).reversed());
        gradesList.sort(Comparator.comparing(Grades::getClassName).reversed());
        for (Grades grades : gradesList) {
            grades.setLessonsort(rowe++);
            grades.setGscot(index++);
        }
        return gradesList;
    }

    /**
     * 分页查询
     * @param limit
     * @param page
     * @param studentName
     * @param className
     * @return
     */
    @GetMapping("grade/restful_lesson")
    public Map<String, Object> findlessonManger(int limit, int page,String studentName,String className){
        String condition = gradesBiz.getCondition(studentName,className);
        // 按条件统计总记录行数
        int count = gradeBiz.selectCount(condition);
        List<Grades> select = gradesBiz.selectByLesson(limit,page-1,condition);
        List<Grades> gradesList =selectById(select);
        Map<String, Object> mapData = new HashMap<String, Object>();
        //在映射集合中添加key为code，值为0的状态码
        mapData.put("code", 0);
        //在映射集合中添加key为msg，值为空字符串的响应信息字符串
        mapData.put("msg", "");
        //在映射集合中添加为count，值为总行数的映射
        mapData.put("count", count);
        //在映射集合中添加key为data，值为成绩对象集合的映射
        mapData.put("data", gradesList);

        //把映射集合响应到客户端
        return mapData;
    }

    /**
     * 循环排名
     * @param gradeList
     * @return
     */
    public List<Grade> fore(List<Grade> gradeList) {
        int index1 = 1;
        int index2 = 1;
        int index3 = 1;
        for (Grade grade: gradeList) {
            if (grade.getLessonId() == 1){
                grade.setLessonSort(index1++);
            }if (grade.getLessonId() == 2){
                grade.setLessonSort(index2++);
            }if (grade.getLessonId() == 3){
                grade.setLessonSort(index3++);
            }
        }
        return gradeList;
    }


    /**
     * 分页显示查询
     * @param limit
     * @param page
     * @param studentName
     * @param className
     * @param schoolName
     * @param lessonName
     * @return
     */
    @GetMapping("grade/restful_lessonalone")
    public Map<String, Object> findlessonMangeralone(int limit, int page, String studentName,String className,String schoolName,String lessonName) {
        // 根据校区名称或学员名称得到条件字符串
        String condition = gradessBiz.getCondition(studentName,className,schoolName,lessonName);
        System.out.println(lessonName);
        // 按条件统计总记录行数
        int count = gradeBiz.selectCount(condition);
        // 按条件分页查询
        List<Grade> glist = gradessBiz.selectByPage(limit, page-1, condition);
        List<Grade> gradeList = fore(glist);
        // 创建一个map，用来存放返回给layui组件需要的键值对
        Map<String, Object> mapData = new HashMap<String, Object>();
        //在映射集合中添加key为code，值为0的状态码
        mapData.put("code", 0);
        //在映射集合中添加key为msg，值为空字符串的响应信息字符串
        mapData.put("msg", "");
        //在映射集合中添加为count，值为总行数的映射
        mapData.put("count", count);
        //在映射集合中添加key为data，值为成绩对象集合的映射
        mapData.put("data", gradeList);

        //把映射集合响应到客户端
        return mapData;
    }

}
